package com.kintreda.ieco_server.util.file;

import com.kintreda.ieco_server.util.DateUtil;
import com.kintreda.ieco_server.util.Parameters;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @Created by IntelliJ IDEA
 * @Author ZhongYao_H
 * @Date 2019/4/13:0:23
 * @Year 2019 Month 04 Day 13
 * @Date_zh 2019 年 四月 星期六
 */

public class FileUploadUtil {

    /**
     *@explain : 图片上传
     *
     * @param file
     *@return  :java.lang.String
     *@author : HuangZhongYao
     *@time   : 2019/4/13 2:37
     */
    public static Map<String,String> uploadImage(MultipartFile file) throws IOException {
        Map<String,String> result = new HashMap<>();
        if (file.isEmpty()) {
            result.put("msg","没有选择文件!");
            result.put("code","500");
            return result;
        }
        String rootpath = Parameters.uploadBasePath;
        long  startTime=System.currentTimeMillis();
        System.out.println("开始上传...");
        String fileName = file.getOriginalFilename().substring(0,file.getOriginalFilename().lastIndexOf("."));
        String perfix   = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
        Set<String>  perfixs = new HashSet<>();
        perfixs.add("gif");
        perfixs.add("jpg");
        perfixs.add("jpeg");
        perfixs.add("png");
        perfixs.add("bmp");
        if (perfixs.add(perfix)){
            result.put("code","500");
            result.put("msg","格式错误:格式不符合 if,jpg,jpeg,png,bmp");
            return result;
        }
        System.out.println("fileName："+fileName);
        String uploadDir = rootpath+File.separator+ DateUtil.getDate(new Date(),DateUtil.YYYYMDD);
        File rootDir = new File(uploadDir);
        if(!rootDir.exists()){
            rootDir.mkdirs();
        }
        String uploadpath = File.separator+ DateUtil.getDate(new Date(),DateUtil.YYYYMDD)+File.separator+DateUtil.getDate(new Date(),DateUtil.YYYY) +DateUtil.getDate(new Date(),DateUtil.MDD) +new Date().getTime()+"."+perfix;

        File newFile=new File(rootpath+uploadpath);
        //通过CommonsMultipartFile的方法直接写文件
        file.transferTo(newFile);
        //压缩图片线程
        FileCompressThread fileCompressThread = new FileCompressThread(rootpath+uploadpath);
        fileCompressThread.start();
        long  endTime=System.currentTimeMillis();
        System.out.println("上传完毕耗时："+String.valueOf(endTime-startTime)+"ms");

        result.put("fileName",fileName);
        result.put("path",newFile.getPath());
        result.put("filepath",uploadpath);
        result.put("msg","上传成功!");
        result.put("code","200");
        result.put("size",file.getSize()+"");
        return result;
    }




}
